package com.lb.statck.controller;

import com.lb.statck.common.result.Result;
import com.lb.statck.mapper.order.OrderMapper;
import com.lb.statck.pojo.dto.PayInfoDto;
import com.lb.statck.pojo.vo.WxPayRespVO;
import com.lb.statck.util.WXPayUtil;
import com.lb.statck.util.WxPayConfig;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAPublicKeyConfig;
//import com.wechat.pay.java.core.cipher.Verifier;
import com.wechat.pay.java.service.payments.jsapi.JsapiService;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayResponse;


import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.function.client.WebClient;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.security.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
 @RestController
@Slf4j
@RequestMapping("/api/weiPay")
public class WeiPayController {

   // private final String apiV3Key;
    @Value("${spring.weixin.mchId}")
    private String mchId;
  @Autowired
  private WebClient webClient;
    @Autowired
    private WxPayConfig wxPayConfig;

     @Value("${wx.miniapp.wechatPayCertificatePath}")
  private  String wechatPayCertificatePath;
    @Value("${spring.weixin.appid}")
    private String appID;
    @Value("${spring.weixin.appsecret}")
    private String appSecret;
    @Value("${wx.miniapp.merchantId}")
    private String merchantId;
    @Value("${wx.miniapp.privateKeyPath}")
    private String privateKeyPath;
    @Value("${wx.miniapp.merchantSerialNumber}")
    private String merchantSerialNumber;
    @Value("${wx.miniapp.apiV3Key}")
    private String apiV3Key;
    @Value("${wx.miniapp.apiV3Key}")
    private String apiV3Key1;

    @Value("${wx.miniapp.payNotifyUrl}")
    private String payNotifyUrl;
    @Value("${wx.miniapp.refundNotifyUrl}")
    private String refundNotifyUrl;
    @Value("${wx.miniapp.publicKeyId}")
    private String publicKeyId;
    @Value("${wx.miniapp.publicKeyPath}")
    private String publicKeyPath;
    @Autowired
    private OrderMapper ordermapper1;
  //  private CertificatesManager certificatesManager;


    //  private final String apiKey;





    @PostMapping("pay")
    public Result pay(@RequestBody PayInfoDto payInfoDto) throws NoSuchAlgorithmException, SignatureException, IOException, URISyntaxException, InvalidKeyException {// 示例代码（Java）
        Map<String, String> params = new HashMap<>();
        params.put("appid", appID);
        params.put("mch_id", mchId);
        params.put("nonce_str", "wdededfefdefefef");
        params.put("body", "商品描述");
        params.put("out_trade_no", payInfoDto.getOrderNo());
        BigDecimal price = ordermapper1.getPrice(payInfoDto.getOrderNo());
        Integer priceInt = price.intValue(); // 可能导致数据丢失或异常

        params.put("total_fee", price.toString());
        params.put("spbill_create_ip", payInfoDto.getIp());
        params.put("notify_url", payInfoDto.getNotifyUrl());
        params.put("trade_type", "JSAPI");
        params.put("openid", payInfoDto.getPayOpenId());
        String requestBody = new JSONObject(params).toString();
        Config config1=new RSAPublicKeyConfig.Builder()
                .merchantId(merchantId)
                .publicKeyId(publicKeyId)
                .publicKeyFromPath(publicKeyPath)
                .privateKeyFromPath(privateKeyPath)
                .merchantSerialNumber(merchantSerialNumber)
                .apiV3Key(apiV3Key)
                .build();

        JsapiService service = new JsapiService.Builder().config(config1).build();

        PrepayRequest request = new PrepayRequest();
        Amount amount = new Amount();
        amount.setTotal(priceInt);
        request.setAmount(amount);
        request.setAppid(appID);
        request.setMchid(mchId);
        request.setDescription("测试商品标题");
        request.setNotifyUrl(payNotifyUrl);
        System.out.println(payNotifyUrl);
        System.out.println("_____________________________");
        request.setOutTradeNo( payInfoDto.getOrderNo());
        Payer payer = new Payer();
        payer.setOpenid( payInfoDto.getPayOpenId());
        request.setPayer(payer);

        PrepayResponse response = service.prepay(request);
        System.out.println(response.getPrepayId());
        //Long timeStamp = System.currentTimeMillis() / 1000;
        Long timeStamp = System.currentTimeMillis() / 1000;
        String timeStampStr = String.valueOf(timeStamp);
        WxPayRespVO vo = new WxPayRespVO();
        vo.setTimeStamp(timeStampStr);
        String substring = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
        vo.setNonceStr(substring);
        String signatureStr = Stream.of(appID, String.valueOf(timeStamp), substring, "prepay_id=" + response.getPrepayId())
                .collect(Collectors.joining("\n", "", "\n"));
        String sign = WXPayUtil.getSign(signatureStr, privateKeyPath);
        vo.setPaySign(sign);
        vo.setSignType("RSA");
        vo.setPrepayId("prepay_id=" + response.getPrepayId());
      //  return vo;
        Result result1 = new Result();
        result1.setData(vo);
        return result1;
        //String url = "https://api.example.com/data";
   //  String response= webClient.post()
        //        .uri("https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi") // 替换为你的目标 URL
      //          .header("Content-Type", "application/json")
        //        .bodyValue(requestBody)
       //         .retrieve()
          //      .bodyToMono(String.class)
         //       .subscribe(responses -> {
         //           System.out.println("Response: " + responses);
           //     }, error -> {
            //        System.err.println("Error: " + error.getMessage());
            //    }).toString();


        // 返回响应内容
        //获取会话密钥（session_key）
       // Result result1 = new Result();
      //  result1.setData(response);
//return result1;
// 调用微信支付统一下单接口
        }

        @PostMapping("/Paynotify")
        public String Paynotify(HttpServletRequest request, HttpServletResponse response) throws IOException {
                 // 获取请求头信息
            return null;
                // 3.查询订单状态是否是未支付，如果是未支付则改为已支付，填充其他逻辑，

                // 4.如果是其他状态综合你的业务逻辑来处理

                // 5.如果是虚拟物品，则对应充值，等等其他逻辑
            }


                // 创建NotificationRequest



    @PostMapping("/Refundnotify")
    public String Refundnotify(HttpServletRequest request, HttpServletResponse response) throws IOException {
       return  null;
    }


}
